<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时天气信息</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2980b9;
            --text-color: #333;
            --light-text: #777;
            --bg-color: #f5f7fa;
            --card-bg: #ffffff;
            --shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Noto Sans SC', sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
            line-height: 1.6;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
        }

        header {
            text-align: center;
            margin-bottom: 30px;
        }

        h1 {
            color: var(--primary-color);
            font-weight: 500;
            margin-bottom: 10px;
        }

        .subtitle {
            color: var(--light-text);
            font-weight: 300;
        }

        .weather-card {
            background-color: var(--card-bg);
            border-radius: 12px;
            box-shadow: var(--shadow);
            padding: 30px;
            margin-bottom: 30px;
            transition: transform 0.3s ease;
        }

        .weather-card:hover {
            transform: translateY(-5px);
        }

        .location {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            border-bottom: 1px solid #eee;
            padding-bottom: 15px;
        }

        .city {
            font-size: 24px;
            font-weight: 500;
        }

        .adcode {
            color: var(--light-text);
            font-size: 14px;
        }

        .weather-main {
            display: flex;
            align-items: center;
            margin-bottom: 25px;
        }

        .weather-icon {
            font-size: 60px;
            margin-right: 20px;
            color: var(--primary-color);
        }

        .temperature {
            font-size: 48px;
            font-weight: 300;
        }

        .weather-desc {
            font-size: 18px;
            color: var(--light-text);
            margin-left: 10px;
        }

        .details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
        }

        .detail-item {
            background-color: rgba(52, 152, 219, 0.1);
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }

        .detail-label {
            font-size: 14px;
            color: var(--light-text);
            margin-bottom: 5px;
        }

        .detail-value {
            font-size: 18px;
            font-weight: 500;
        }

        .report-time {
            text-align: right;
            font-size: 14px;
            color: var(--light-text);
            margin-top: 20px;
        }

        .refresh-btn, .copy-btn {
            display: block;
            width: 100%;
            padding: 12px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
            margin-bottom: 10px;
        }

        .refresh-btn:hover, .copy-btn:hover {
            background-color: var(--secondary-color);
        }

        .back-btn {
            position: absolute;
            top: 20px;
            left: 20px;
            padding: 10px 15px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .ai-response-container {
            margin-top: 20px;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 8px;
            display: none;
        }

        .ai-input-container {
            margin-top: 20px;
        }

        .ai-input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-bottom: 10px;
            height: 80px;
            resize: vertical;
        }

        .send-ai-btn {
            padding: 10px 15px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .copy-success {
            display: none;
            color: #27ae60;
            font-size: 14px;
            margin-top: 10px;
        }

        .ai-chat-container {
            margin-top: 20px;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 8px;
            max-height: 300px;
            overflow-y: auto;
        }

        .ai-message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 8px;
        }

        .user-message {
            background-color: #e3f2fd;
            text-align: right;
        }

        .assistant-message {
            background-color: #f1f8e9;
        }

        .system-message {
            background-color: #fff3e0;
        }

        @media (max-width: 600px) {
            .weather-main {
                flex-direction: column;
                text-align: center;
            }

            .weather-icon {
                margin-right: 0;
                margin-bottom: 15px;
            }

            .details {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <button class="back-btn" id="back-btn">
        <i class="fas fa-arrow-left"></i> 返回
    </button>

    <div class="container">
        <header>
            <h1>实时天气信息</h1>
            <p class="subtitle">获取您所在城市的最新天气数据</p>
        </header>

        <div class="weather-card">
            <div class="location">
                <div>
                    <div class="city" id="city">加载中...</div>
                    <div class="adcode" id="adcode"></div>
                </div>
                <div class="report-time" id="reporttime"></div>
            </div>

            <div class="weather-main">
                <i class="fas fa-sun weather-icon" id="weather-icon"></i>
                <div>
                    <span class="temperature" id="temperature">--</span>
                    <span class="weather-desc" id="weather">--</span>
                </div>
            </div>

            <div class="details">
                <div class="detail-item">
                    <div class="detail-label">风向</div>
                    <div class="detail-value" id="winddirection">--</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">风力</div>
                    <div class="detail-value" id="windpower">--</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">湿度</div>
                    <div class="detail-value" id="humidity">--</div>
                </div>
            </div>

            <button class="refresh-btn" id="refresh-btn">
                <i class="fas fa-sync-alt"></i> 刷新数据
            </button>

            <button class="copy-btn" id="copy-btn">
                <i class="fas fa-copy"></i> 复制到剪贴板
            </button>

            <div class="ai-input-container">
                <textarea class="ai-input" id="ai-input" placeholder="输入您想发送给AI的消息..."></textarea>
                <button class="send-ai-btn" id="send-ai-btn">发送给AI</button>
            </div>

            <div class="ai-chat-container" id="ai-chat-container">
                <!-- AI聊天记录将在这里显示 -->
            </div>

            <div class="copy-success" id="copy-success">
                天气信息已复制到剪贴板！
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始加载数据
            fetchWeatherData();

            // 绑定刷新按钮事件
            document.getElementById('refresh-btn').addEventListener('click', fetchWeatherData);

            // 绑定返回按钮事件
            document.getElementById('back-btn').addEventListener('click', function() {
                window.history.back();
            });

            // 绑定发送给AI按钮事件
            document.getElementById('send-ai-btn').addEventListener('click', function() {
                const message = document.getElementById('ai-input').value.trim();
                if (!message) {
                    alert('请输入消息内容');
                    return;
                }

                // 清空输入框
                document.getElementById('ai-input').value = '';

                // 发送消息到AI
                sendMessageToAI(message);
            });

            // 绑定复制到剪贴板按钮事件
            document.getElementById('copy-btn').addEventListener('click', function() {
                const city = document.getElementById('city').textContent;
                const temperature = document.getElementById('temperature').textContent;
                const weather = document.getElementById('weather').textContent;
                const humidity = document.getElementById('humidity').textContent;

                if (city === '加载中...' || city === '获取数据失败') {
                    alert('请先获取有效的天气数据');
                    return;
                }

                // 构建要复制的文本
                const weatherText = `${city}的当前天气：${weather}，温度：${temperature}，湿度：${humidity}`;

                // 创建一个临时的textarea元素
                const textarea = document.createElement('textarea');
                textarea.value = weatherText;
                document.body.appendChild(textarea);

                // 选择并复制文本
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);

                // 显示成功提示
                document.getElementById('copy-success').style.display = 'block';

                // 3秒后隐藏提示
                setTimeout(function() {
                    document.getElementById('copy-success').style.display = 'none';
                }, 3000);
            });
        });

        // 获取当前用户的ID和对话ID
        const userId = localStorage.getItem('user_id');
        let conversationId = sessionStorage.getItem('conversation_id') || null;

        function fetchWeatherData() {
            // 显示加载状态
            document.getElementById('city').textContent = '加载中...';
            document.getElementById('temperature').textContent = '--';

            fetch('/api/weather')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        throw new Error(data.error);
                    }

                    // 更新页面数据
                    updateWeatherUI(data);
                })
                .catch(error => {
                    console.error('获取天气数据失败:', error);
                    document.getElementById('city').textContent = '获取数据失败';
                    document.getElementById('temperature').textContent = '--';
                    document.getElementById('weather').textContent = error.message;
                });
        }

        function updateWeatherUI(data) {
            // 更新基本信息
            document.getElementById('city').textContent = data.city;
            document.getElementById('adcode').textContent = `行政编码: ${data.adcode}`;
            document.getElementById('weather').textContent = data.weather;
            document.getElementById('temperature').textContent = `${data.temperature}°C`;
            document.getElementById('winddirection').textContent = data.winddirection;
            document.getElementById('windpower').textContent = data.windpower;
            document.getElementById('humidity').textContent = `${data.humidity}%`;
            document.getElementById('reporttime').textContent = `更新时间: ${data.reporttime}`;

            // 根据天气类型设置图标
            setWeatherIcon(data.weather);
        }

        function setWeatherIcon(weather) {
            const icon = document.getElementById('weather-icon');
            weather = weather.toLowerCase();

            // 清除所有可能的类
            icon.className = 'fas weather-icon';

            if (weather.includes('晴')) {
                icon.classList.add('fa-sun');
            } else if (weather.includes('云') || weather.includes('阴')) {
                icon.classList.add('fa-cloud');
            } else if (weather.includes('雨')) {
                icon.classList.add('fa-cloud-rain');
            } else if (weather.includes('雪')) {
                icon.classList.add('fa-snowflake');
            } else if (weather.includes('雾') || weather.includes('霾')) {
                icon.classList.add('fa-smog');
            } else if (weather.includes('雷')) {
                icon.classList.add('fa-bolt');
            } else {
                icon.classList.add('fa-cloud-sun');
            }
        }

        function sendMessageToAI(message) {
            const chatContainer = document.getElementById('ai-chat-container');

            // 添加用户消息到聊天界面
            const userMessageDiv = document.createElement('div');
            userMessageDiv.className = 'ai-message user-message';
            userMessageDiv.textContent = message;
            chatContainer.appendChild(userMessageDiv);

            // 显示加载状态
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'ai-message system-message';
            loadingDiv.textContent = '正在获取AI回答...';
            chatContainer.appendChild(loadingDiv);

            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;

            // 构造请求数据
            const data = {
                message: message,
                conversation_id: conversationId || null,
                role_id: 2,
                user_id: userId, // 假设有一个默认的用户ID
            };

            // 发送请求到AI
            fetch('/api/send_weather', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-User-ID': userId // 传递用户ID
                },
                credentials: 'include',
                body: JSON.stringify(data),
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
            if (data.success) {
                // 检查是否为 Response 对象
                let aiResponse = data.response;
                if (typeof aiResponse === 'object' && 'json' in aiResponse) {
                    aiResponse = aiResponse.json(); // 如果是 Response 对象，提取 JSON
                }

                // 移除加载提示
                chatContainer.removeChild(loadingDiv);

                // 添加AI回复到聊天界面
                const aiMessageDiv = document.createElement('div');
                aiMessageDiv.className = 'ai-message assistant-message';
                aiMessageDiv.textContent = aiResponse; // 使用提取后的数据
                chatContainer.appendChild(aiMessageDiv);

                // 更新对话ID
                conversationId = data.conversation_id;
                sessionStorage.setItem('conversation_id', conversationId);

                // 滚动到底部
                chatContainer.scrollTop = chatContainer.scrollHeight;
            } else {
                // 显示错误信息
                loadingDiv.textContent = '获取AI回答失败: ' + data.error;
            }
        })
            .catch(error => {
                console.error('发送消息到AI失败:', error);
                loadingDiv.textContent = '获取AI回答失败: ' + error.message;
            });
        }
    </script>
</body>
</html>